package com.spring.cloud.eurekaclientzuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.jmnarloch.spring.cloud.ribbon.support.RibbonFilterContextHolder;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

//灰度发布 过滤器 要求服务提供方 提供 eureka.instance.metadata-map.gray-release:1

@Component
public class GrayReleaseZuulFilter extends ZuulFilter {
    //灰色发布控制参数名称
    private final static String GRAY_PARAM = "gray-release";
    //灰色发布启用标记
    private final static String GRAY_ENABLE = "1";
    //灰色发布禁用标记
    private final static String GRAY_DISABLE = "0";

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER+31;
    }

    @Override
    public boolean shouldFilter() {

        //获取上下文
        RequestContext ctx = RequestContext.getCurrentContext();
        //获取uri
        String uri = ctx.getRequest().getRequestURI();

        //判断URI 前缀 以什么开头 通过
        return uri.startsWith("/u/") || uri.startsWith("/user/") || uri.startsWith("/user-api");
    }

    @Override
    public Object run() throws ZuulException {

        //获取上下文
        RequestContext ctx = RequestContext.getCurrentContext();
        //获取请求控制参数
        String grayHead = ctx.getRequest().getParameter(GRAY_PARAM);
        //不存在请求参数或参数不为灰色发布标志,则只请求正常发布的服务实例
        if(StringUtils.isBlank(grayHead) || !GRAY_ENABLE.equals(grayHead)){
            //设置元数据过滤条件
            RibbonFilterContextHolder.getCurrentContext().add(GRAY_PARAM,GRAY_DISABLE);
        }else{  //不存在灰色发布参数,且参数有效
            //设置元数据过滤条件
            RibbonFilterContextHolder.getCurrentContext().add(GRAY_PARAM,GRAY_ENABLE);
        }
        return null;
    }
}
